package com.clockey.server.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.clockey.server.dao.FriendMapper;
import com.clockey.server.dao.FriendRequestMapper;
import com.clockey.server.dao.UserMapper;
import com.clockey.server.enums.HandleResult;
import com.clockey.server.pojo.Friend;
import com.clockey.server.pojo.FriendRequest;
import com.clockey.server.pojo.User;
import com.clockey.server.service.FriendService;

@Service
public class FriendServiceImpl implements FriendService {

	@Autowired
	private FriendRequestMapper friendRequestMapper;

	@Autowired
	private FriendMapper friendMapper;

	@Autowired
	private UserMapper userMapper;

	@Override
	public void sendAddFriendRequest(Map<String, Object> map) {
		FriendRequest friendRequest = (FriendRequest) map.get("friendRequest");
		friendRequestMapper.insert(friendRequest);
		// 推送消息给处理者
	}

	@Override
	public void handAddFriendRequest(Map<String, Object> map) {
		FriendRequest friendRequest = (FriendRequest) map.get("friendRequest");
		friendRequestMapper.update(friendRequest);
		if (HandleResult.APPROVE.getResult() == friendRequest.getHandResult()) {
			List<Friend> Friends = new ArrayList<Friend>();
			Friend sender = new Friend();
			sender.setUserId(friendRequest.getSendUserId());
			sender.setFriendUserId(friendRequest.getHandUserId());
			Friends.add(sender);
			Friend handle = new Friend();
			sender.setFriendUserId(friendRequest.getSendUserId());
			sender.setUserId(friendRequest.getHandUserId());
			Friends.add(handle);
			friendMapper.batchInsert(Friends);
		}
	}

	@Override
	public void deleteFriends(Map<String, Object> map) {
		friendMapper.delete(map);
	}

	@Override
	public JSONArray list(Map<String, Object> map) {
		JSONArray jsonArray = new JSONArray();
		List<Friend> friends = friendMapper.list(map);
		for (Friend friend : friends) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("remarks", friend.getRemarks());
			User user = userMapper.select(friend.getFriendUserId());
			jsonObject.put("phone", user.getPhone());
			jsonObject.put("userName", user.getUserName());
			jsonArray.add(jsonObject);
		}
		return jsonArray;
	}

}
